import Taro from '@tarojs/taro';
import { auth2Session } from '../service/ouath';

import { OK_CODE, ERROR_CODE, USER_INFO, TOKEN } from '../code'

/**
 * Promise封装wx.checkSession
 */
 function checkSession() {
    return new Promise(function(resolve, reject) {
        Taro.checkSession({
            success: function() {
                resolve(true);
            },
            fail: function() {
                reject(false);
            }
        })
    });
}

/**
 * 判断用户是否登录
 */
 export function chackLogin() {
    return new Promise(function(resolve, reject){
        if( Taro.getStorageSync(USER_INFO) && Taro.getStorageSync(TOKEN) ){
            checkSession().then(() => {
                resolve(true);
            }).catch(() => {
                reject(false);
            });
        }else{
            reject(false);
        }
    });
}

/**
 * Promise封装wx.login
 */
 function login() {
    return new Promise(function(resolve, reject) {
        Taro.login({
            success: function(res) {
                if (res.code) {
                    resolve(res);
                } else {
                    reject(res);
                }
            },
            fail: function(err) {
                reject(err);
            }
        });
    });
}

/**
 * 调用微信登录
 */

 export function loginByWeixin() {
    return new Promise(function(resolve, reject) {
        return login().then((res) => {
            console.log('res', res);
            const param = global();
            param.requestData = {
                code: res.code
            }
            // 授信认证
            auth2Session(param).then(authRes => {
                let data = authRes.data;
                if( data.code == OK_CODE ){
                    var json = data.responseData;
                    Taro.setStorageSync(USER_INFO, userInfo);
                    Taro.setStorageSync(TOKEN, JSON.stringify(json));
                }
                resolve(authRes);
            }).catch(err => {
                reject(err);
            });
        }).catch((err) => {
            reject(err);
        })
    });
}
  